/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * RegistrarZona.java
 *
 * Created on 28/03/2011, 11:40:20 AM
 */

package zonasoft.Vistas.Negocio;

import com.mysql.jdbc.Connection;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import zonasoft.Conceptos.Especiales.Departamentos;
import zonasoft.Conceptos.Especiales.Municipios;
import zonasoft.Conceptos.Zona;
import zonasoft.Manejadores.ManejadorBaseDatos;
import zonasoft.Manejadores.ManejadorDepartamentos;
import zonasoft.Manejadores.ManejadorMunicipios;
import zonasoft.Manejadores.ManejadorZona;
import zonasoft.Vistas.VentanaPrincipal;

/**
 *
 * @author Usuario
 */
public class RegistrarZona extends javax.swing.JDialog {

    HashMap<String,Integer> departamentos;
    HashMap<String,Integer> municipios;
    /** Creates new form RegistrarZona */
    public RegistrarZona(java.awt.Frame parent) {
        super(parent, true);
        initComponents();
          pack();
        Rectangle parentBounds = parent.getBounds();
        Dimension size = getSize();
        // Center in the parent
        int x = Math.max(0, parentBounds.x + (parentBounds.width - size.width) / 2);
        int y = Math.max(0, parentBounds.y + (parentBounds.height - size.height) / 2);
        setLocation(new Point(x, y));
    }

    Zona zo = null;
    ManejadorZona mz = new ManejadorZona();
     
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jXTaskPaneContainer1 = new org.jdesktop.swingx.JXTaskPaneContainer();
        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        comboDepartamento = new javax.swing.JComboBox();
        jPanel3 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        campoCodigo = new javax.swing.JTextField();
        comboMunicipios = new javax.swing.JComboBox();
        jPanel4 = new javax.swing.JPanel();
        botonGuardar = new javax.swing.JButton();
        botonCancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Lucida Bright", 1, 18)); // NOI18N
        jLabel1.setText("Registro de Zona");
        jXTaskPaneContainer1.add(jLabel1);

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, java.awt.Color.lightGray, java.awt.Color.lightGray, java.awt.Color.black, java.awt.Color.black), "Datos Generales", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Lucida Bright", 1, 12))); // NOI18N

        jLabel2.setFont(new java.awt.Font("Lucida Bright", 0, 12)); // NOI18N
        jLabel2.setText("Departamento");

        jLabel3.setFont(new java.awt.Font("Lucida Bright", 0, 12)); // NOI18N
        jLabel3.setText("Municipio");

        listaraDepartamento();
        comboDepartamento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboDepartamentoActionPerformed(evt);
            }
        });

        jPanel3.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, java.awt.Color.black, java.awt.Color.black, java.awt.Color.lightGray, java.awt.Color.lightGray));

        jLabel5.setFont(new java.awt.Font("Lucida Bright", 0, 12)); // NOI18N
        jLabel5.setText("Codigo");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addComponent(jLabel5)
                .addGap(34, 34, 34)
                .addComponent(campoCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(53, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(campoCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addContainerGap(33, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(comboDepartamento, 0, 165, Short.MAX_VALUE)
                            .addComponent(comboMunicipios, 0, 165, Short.MAX_VALUE))))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(comboDepartamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(28, 28, 28)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(comboMunicipios, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(29, 29, 29)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, java.awt.Color.lightGray, java.awt.Color.lightGray, java.awt.Color.black, java.awt.Color.black));

        botonGuardar.setFont(new java.awt.Font("Lucida Bright", 1, 12)); // NOI18N
        botonGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/zonasoft/Vistas/iconos/Floppy-icon.png"))); // NOI18N
        botonGuardar.setText("Guardar");
        botonGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonGuardarActionPerformed(evt);
            }
        });

        botonCancelar.setFont(new java.awt.Font("Lucida Bright", 1, 12)); // NOI18N
        botonCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/zonasoft/Vistas/iconos/Delete-icon.png"))); // NOI18N
        botonCancelar.setText("Cancelar");
        botonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(botonGuardar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(botonCancelar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(botonGuardar)
                .addGap(34, 34, 34)
                .addComponent(botonCancelar)
                .addContainerGap(27, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addComponent(jXTaskPaneContainer1, javax.swing.GroupLayout.PREFERRED_SIZE, 534, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jXTaskPaneContainer1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(53, 53, 53)
                        .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(51, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonCancelarActionPerformed
        // TODO add your handling code here:
         int resp = JOptionPane.showConfirmDialog(this, "Seguro que deseas cerrar la Ventana ","Warning", JOptionPane.YES_NO_OPTION);
        if(resp == JOptionPane.YES_OPTION){
            this.dispose();
        }
}//GEN-LAST:event_botonCancelarActionPerformed

    private void botonGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonGuardarActionPerformed
        // TODO add your handling code here:
if((comboDepartamento.getSelectedIndex() == 0) ){
 JOptionPane.showMessageDialog(null, "no se ha seleccionado ubicacion de la zona");
    } else if(campoCodigo.getText().isEmpty()){
 JOptionPane.showMessageDialog(null, "no se ha seleccionado el identificador de la zona");
     }else{
            try {
                ManejadorBaseDatos mb = ManejadorBaseDatos.getInstancia();
                mb.conectar();
                ManejadorZona.con = (Connection) mb.getConexion();
                if(ManejadorZona.getZona(campoCodigo.getText())!=null){
                JOptionPane.showMessageDialog(null,"Esta zona se encuentra registrada para este municipio en este departamento ","error",JOptionPane.WARNING_MESSAGE);
                }else{
                  zo = new Zona();
                  zo.setCodigoZona(campoCodigo.getText());;
                  String nombreMun = comboMunicipios.getSelectedItem().toString();
                 
                  int idMun =(municipios.get(nombreMun));

                  zo.setIdMunicipio(String.valueOf(idMun));
                mz.crearZona(zo);
                JOptionPane.showMessageDialog(null, "Zona Creada exitosamente");
                campoCodigo.setText("");
                   }
            }catch (Exception ex) {
                Logger.getLogger(RegistrarZona.class.getName()).log(Level.SEVERE, null, ex);
                ex.printStackTrace();
            }
     }
        
    }//GEN-LAST:event_botonGuardarActionPerformed

    private void comboDepartamentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboDepartamentoActionPerformed
        // TODO add your handling code here:
         // TODO add your handling code here:
      String id=  comboDepartamento.getSelectedItem().toString();
      int indice=comboDepartamento.getSelectedIndex();
//        System.out.println("id = " + id);
//        System.out.println("indice = " + indice);
      if(indice!=0)
      {
          Integer IdDepartamento=departamentos.get(id);
//          System.out.println("IdDepartamento = " + IdDepartamento);
        listaraMunicipios(String.valueOf(IdDepartamento));
        comboMunicipios.setEnabled(true);
      }
      else
          JOptionPane.showMessageDialog(null, "Seleccione un departamento primero");

    }//GEN-LAST:event_comboDepartamentoActionPerformed

    /**
    * @param args the command line arguments
   
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                RegistrarZona dialog = new RegistrarZona(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
 */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonCancelar;
    private javax.swing.JButton botonGuardar;
    private javax.swing.JTextField campoCodigo;
    private javax.swing.JComboBox comboDepartamento;
    private javax.swing.JComboBox comboMunicipios;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private org.jdesktop.swingx.JXTaskPaneContainer jXTaskPaneContainer1;
    // End of variables declaration//GEN-END:variables

      public void listaraDepartamento(){
    ManejadorBaseDatos  mbd = ManejadorBaseDatos.getInstancia();
    departamentos = new HashMap<String,Integer>();
      try{
       mbd.conectar();
       ManejadorDepartamentos.con =  (Connection) mbd.getConexion();
        comboDepartamento.removeAllItems();

        List listarDepartamento = null;
              listarDepartamento=ManejadorDepartamentos.listarDepartamentos();
              Iterator<Departamentos> iter = listarDepartamento.iterator();
              Departamentos dep = null;
              comboDepartamento.addItem("--Seleccione un departamento---");
              while (iter.hasNext()){
                dep = iter.next();
                int codigoDepartamento = Integer.parseInt(dep.getCodigoDepartamento());
                comboDepartamento.addItem(dep.getNombre());
               departamentos.put(dep.getNombre(), codigoDepartamento) ;
                }
              }catch (Exception ex){
                ex.printStackTrace();
              }

        } // fin de listar departamentos

      public void listaraMunicipios(String idDepartamentos){
            ManejadorBaseDatos mbd = ManejadorBaseDatos.getInstancia();
            municipios = new HashMap<String,Integer>();
            try{
             mbd.conectar();
             ManejadorMunicipios.con = (Connection) mbd.getConexion();
             comboMunicipios.removeAllItems();
           List listarMunicipios = null;
           listarMunicipios = ManejadorMunicipios.listarMunicipios(idDepartamentos);
           Iterator<Municipios> iter = listarMunicipios.iterator();
           Municipios mun = null;
               while (iter.hasNext()){
           mun = iter.next();
           int codigoMunicipio = Integer.parseInt(mun.getCodigoMunicipio());
           comboMunicipios.addItem(mun.getNombre());
           municipios.put(mun.getNombre(), codigoMunicipio);
            }

           comboMunicipios.setSelectedIndex(8);
            }catch(Exception ex){
              ex.printStackTrace();
            }
        }// fin del listar Municipios

}
